<template>
  <el-dialog :visible.sync="dialogVisible" title="学生提问审核" width="30%" style="min-width: 400px;" @open="onDialogOpen">
    <div v-if="questions.length > 0" style="display: flex; flex-direction: column; justify-content: center; align-items: center;">
      <div style="text-align: left; margin-bottom: 10px; width: 100%;" >请审核以下学生提问</div>
      <div style="text-align: left; margin-bottom: 10px; width: 100%;">提问学生：{{ questions[currentPage].asked_by.username }}</div>
      <el-input type="textarea" :rows="4" :value="questions[currentPage].content" readonly></el-input>
      <div style="display: flex; justify-content: center; margin-top: 20px;">
        <el-button style="margin-right: 10px;" @click="emits('auditQuestion-canceled')">取消</el-button>
        <el-button type="primary" style="margin-right: 10px;" @click="onAudit">通过</el-button>
        <el-button type="danger" @click="onReject">不合理</el-button>
      </div>
    </div>
    <div v-else>
      <el-text class="mx-1">没有问题需要审核</el-text>
    </div>
    <div slot="footer" class="dialog-footer" style="display: flex; flex-direction: column; justify-content: center; align-items: center; margin-top: 20px;">
      <el-pagination
          @current-change="page=>{currentPage=page-1}"
          background
          layout="prev, pager, next"
          :page-count="total"
          class="mt-4"
        />
    </div>
  </el-dialog>
</template>
<script setup>

import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { loadQuestionsToAudited, auditQuestion, rejectQuestion } from '../utils/apiQuestion.js'

const questions = ref ([])
const dialogVisible = ref(false);
const total = ref(0);
const currentPage = ref(0);

const loadQuestions = () => {
  loadQuestionsToAudited().then(res=>{
    questions.value = res.data
    total.value = res.data.length
    if (total.value <= currentPage.value) {
      currentPage.value = 0
    }
  })
}

const onReject = () => {
  rejectQuestion(questions.value[currentPage.value].id).then(res=>{
    loadQuestions()
    ElMessage.warning('已拒绝！')
  })
}

const onAudit = () => {
  auditQuestion(questions.value[currentPage.value].id).then(res=>{
    loadQuestions()
    ElMessage.success('审核成功！')
  })
}

const onDialogOpen = () => {
  loadQuestions()
}

const emits = defineEmits(['auditQuestion-canceled'])

</script>